<template>
  <div class='pubedit'>

    <div style='border: 1px solid #ccc;'>
      <Toolbar
        style='border-bottom: 1px solid #ccc'
        :editor='editorRef'
        :defaultConfig='toolbarConfig'
        :mode='mode'
      />
      <Editor
        style='height: 45vh; overflow-y: hidden;'
        v-model='editContent'
        :defaultConfig='editorConfig'
        @onCreated='handleCreated'
        @onChange='handleChange'
        :mode='mode'
      />
    </div>

  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { filterSize, getFilePath, getFileName } from '@/utils/common';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';

import { createOss } from '@/utils/alioss.js';


const props = defineProps({
  editContent: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
});
const emits = defineEmits(['editContentEnv']);


const editContent = ref('');
editContent.value = props.editContent;

const editorRef = shallowRef();
const mode = ref('default');
const loading = ref(false);

watch(() => props.editContent, (nv) => {
  editContent.value = nv;
});

const toolbarConfig = {
  excludeKeys: [
    'insertVideo',
    'insertImage',
  ],
};

const editorConfig = {

  placeholder: props.placeholder,
  MENU_CONF: {},
};


//自定义富文本编辑器上传图片
editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    pushOssServeImg(file).then(res => {
      insertFn(res.url);
    });
  },
};


//图片上传oss的操作
const pushOssServeImg = (file) => {
  return new Promise(async (resolve, reject) => {
    let client = await createOss();
    client.put(getFilePath() + getFileName(file.name), file).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
};


// 点击菜单上传视频
editorConfig.MENU_CONF['uploadVideo'] = {
  // 自定义上传视频
  customUpload(file, insertFn) {

    if (!(file.type.match(/mp4/i) || file.type.match(/webm/i) || file.type.match(/ogg/i))) {
      ElMessage.error('视频只支持 mp4、ogg、webm 格式请自行转化后再上传！');
      return;
    }

    if (file.size > 52428800) {
      ElMessageBox.confirm(`该视频${filterSize(file.size)}上传速度较慢，可选择下方大附件上传！`, '温馨提示', {
        confirmButtonText: '换种方式',
        cancelButtonText: '仍然坚持上传',
        type: 'warning',
      }).then(() => {

      }).catch(() => {
        pushVidFn(file).then(r => {
          insertFn(r);
        });
      });
    } else {
      pushVidFn(file).then(r => {
        insertFn(r);
      });
    }
  },
};


//视频上传方法
const pushVidFn = (file) => {
  loading.value = ding.service({
    lock: true,
    text: '上传中请稍后...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  return new Promise((resolve, reject) => {
    pushOssVideo(file).then(res => {
      let requrl = res.res.requestUrls[0];
      let index = requrl.lastIndexOf('?');
      requrl = requrl.substring(0, index);
      resolve(requrl);
      loading.value.close();
    });

  });
};


//视频上传到oss的操作
const pushOssVideo = (file) => {
  return new Promise((resovle, reject) => {
    createOss().then((client) => {
      client.multipartUpload(getFilePath() + getFileName(file.name), file, {
        progress: (p, cpt, res) => {
          loading.value.text = '上传进度' + parseInt(p * 100) + '%';
        },
      }).then(res => {
        resovle(res);
        loading.close();
      }).catch(err => {
        reject(err);
      });
    });
  });
};


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});


const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // console.log( editor.getMenuConfig('insertVideo') )
  // console.log(editor.getAllMenuKeys())
  // console.log(editor.getConfig())
};

const handleChange = (editor) => {
  emits('editContentEnv', editor.getHtml());
};


</script>

<style lang='scss' scoped>
.pubedit {
  width: 100%;
}

</style>
